package com.it.commicity.controller.zy;


import com.alibaba.excel.EasyExcel;
import com.it.commicity.common.Result;
import com.it.commicity.common.ResultCodeEnum;
import com.it.commicity.config.exception.ExcelException;
import com.it.commicity.domain.po.ZyUnit;
import com.it.commicity.domain.requestPass.Unit;
import com.it.commicity.domain.vo.RoomVo;
import com.it.commicity.domain.vo.UnitVo;
import com.it.commicity.service.zy.IZyUnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 单元  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-07-11
 */
@RestController
@RequestMapping("/api/unit")
public class ZyUnitController {
    @Autowired
    private IZyUnitService unitService;

    //分页查询数据
    @GetMapping("/selectUnitList")
    public Result selectUnitList(Unit unit) {
        System.out.println(unit.toString());
        return unitService.selectUnitList(unit);
    }

    @PostMapping("/getExcel")
    public void getExcel(@RequestBody ArrayList<Long> unitIds,
                         @RequestParam Long communityId, HttpServletResponse response) {
        try {
            // 1. 查询数据（根据IDs获取要导出的数据列表）
            List<UnitVo> dataList = unitService.getExportData(unitIds, communityId);
            // 2. 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            String fileName = URLEncoder.encode("单元信息.xls", "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 3. 使用EasyExcel导出
            EasyExcel.write(response.getOutputStream(), UnitVo.class)
                    .sheet("单元数据")
                    .doWrite(dataList);
        } catch (Exception e) {
            System.err.println(e);
            throw new ExcelException(ResultCodeEnum.EXCEL_EXPORT_ERROR);
        }
    }

    @PostMapping("/updateAndSaveUnit")
    public Result updateAndSaveUnit(@RequestBody ZyUnit zyUnit) {
        System.err.println("zy-ZyUnitController-updateAndSaveUnit->" + zyUnit);
//        return unitService.updateAndSaveZyRoom(zyUnit);
        return Result.fail("1");
    }
}
